package com.whfc.wxmp.exception;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultEnum;
import org.apache.dubbo.rpc.RpcException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuguocheng
 * @desc 全局异常处理
 * @date 2019-07-20
 */
@ControllerAdvice("com.whfc")
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Result exceptionHandler(Exception ex) {
        logger.error("Exception:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg(ResultEnum.FAILURE.getMessage());
        return message;
    }

    @ExceptionHandler(value = {BizException.class})
    @ResponseBody
    public Result bizExceptionHandler(BizException ex) {
        logger.error("BizException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ex.getCode());
        message.setMsg(ex.getMsg());
        return message;
    }

    @ExceptionHandler(value = {RpcException.class})
    @ResponseBody
    public Result rpcExceptionHandler(RpcException ex) {
        logger.error("RpcException:msg=" + ex.getMessage(), ex);
        if (ex.isTimeout()) {
            logger.error("rpc,timeout");
        } else if (ex.isNoInvokerAvailableAfterFilter()) {
            logger.error("rpc,no-service-provider");
        } else if (ex.isNetwork()) {
            logger.error("rpc,network-error");
        } else if (ex.isSerialization()) {
            logger.error("rpc,serialization-error");
        } else if (ex.isBiz()) {
            logger.error("rpc,biz-error");
        } else if (ex.isLimitExceed()) {
            logger.error("rpc,limit-exceed-error");
        } else {
            logger.error("rpc,unknown-error");
        }
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg("RPC服务调用异常!");
        return message;
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Result methodArgumentValidExceptionHandler(MethodArgumentNotValidException ex) {
        logger.error("MethodArgumentNotValidException:msg=" + ex.getMessage(), ex);
        BindingResult result = ex.getBindingResult();
        List<String> fieldErrors = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> errorList = result.getAllErrors();
            for (ObjectError error : errorList) {
                FieldError fieldError = (FieldError) error;
                fieldErrors.add(String.format("%s:%s", fieldError.getField(), fieldError.getDefaultMessage()));
            }
        }

        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg("参数验证失败");
        message.setData(fieldErrors);
        return message;
    }

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    @ResponseBody
    public Result missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException ex) {
        logger.error("MissingServletRequestParameterException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg(String.format("缺少参数:%s,类型:%s", ex.getParameterName(), ex.getParameterType()));
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {ConstraintViolationException.class})
    @ResponseBody
    public Result constraintViolationExceptionHandler(ConstraintViolationException ex) {
        logger.error("ConstraintViolationException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg(String.format("参数错误:%s", ex.getMessage()));
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
    @ResponseBody
    public Result methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
        logger.error("MethodArgumentTypeMismatchException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg(String.format("参数%s类型不正确", ex.getName()));
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    @ResponseBody
    public Result httpMessageNotReadableException(HttpMessageNotReadableException ex) {
        logger.error("HttpMessageNotReadableException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.FAILURE.getCode());
        message.setMsg("参数格式不正确");
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result httpMessageNotReadableException(BindException ex) {
        logger.error("BindException:msg=" + ex.getMessage(), ex);
        List<String> errorMsgList = new ArrayList<>();
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            String errorField = error.getField();
            String errorMsg = error.getDefaultMessage();
            errorMsgList.add(String.format("参数:%s,%s", errorField, errorMsg));
        }
        Result message = new Result();
        message.setCode(ResultEnum.PARAM_ERROR.getCode());
        message.setMsg("参数错误");
        message.setData(errorMsgList);
        return message;
    }


    @ExceptionHandler(value = {AuthenticationException.class})
    @ResponseBody
    public Result authenticationException(AuthenticationException ex) {
        logger.error("AuthenticationException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.AUTHC_ERROR.getCode());
        message.setMsg(ResultEnum.AUTHC_ERROR.getMessage());
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {AuthorizationException.class})
    @ResponseBody
    public Result authorizationException(AuthorizationException ex) {
        logger.error("AuthorizationException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.AUTHZ_ERROR.getCode());
        message.setMsg(ResultEnum.AUTHZ_ERROR.getMessage());
        message.setData(null);
        return message;
    }

    @ExceptionHandler(value = {IncorrectCredentialsException.class})
    @ResponseBody
    public Result incorrectCredentialsException(IncorrectCredentialsException ex) {
        logger.error("IncorrectCredentialsException:msg=" + ex.getMessage(), ex);
        Result message = new Result();
        message.setCode(ResultEnum.AUTHC_ERROR.getCode());
        message.setData(null);
        message.setMsg("账号或密码错误");
        return message;
    }

}
